<?php namespace App\Modules\Admin\Controllers;

// Models
use App\Models\Settings;
use App\Models\User;
use App\Models\UserRole;
use App\Models\Role;
//Requests
use Illuminate\Http\Request;
use App\Modules\Admin\Requests\Users\AddRequest;
use App\Modules\Admin\Requests\Users\EditRequest;
use App\Modules\Admin\Requests\Users\SearchRequest;
use Todstoychev\Icr\Icr as ToIcr;
use App\Modules\Admin\Controllers\Controller;

/**
 * Controller used to handle user actions in the admin part.
 * Adding user, deleting user and etc.
 *
 * @author Todor Todorov <todstoychev@gmail.com>
 * @package App\Http\Controllers\Admin
 */
class AdminUsersController extends Controller
{

    /**
     * @inheritdoc
     */
    public function __construct()
    {
        parent::__construct();
        $this->middleware(
            'force_https',
            [
                'only' => [
                    'getAdd',
                    'postAdd',
                ],
            ]
        );
    }

    /**
     * define action names
     * @var array
     */
    public static $actionNames = [
        'getAll'=>'访问用户列表',
        'postSearch'=>'执行用户搜索',
        'getAdd'=>'访问添加用户',
        'postAdd'=>'执行添加用户',
        'getDelete'=>'执行删除用户',
        'getEdit'=>'访问编辑用户',
        'postEdit'=>'执行编辑用户',
        'getDeleteAvatar'=>'执行用户头像',
        'getDisable'=>'执行禁用用户',
        'getActivate'=>'执行启用用户',
    ];

    /**
     * Renders all page
     *
     * @param Request $request
     *
     * @internal param int $limit Items per page
     * @internal param string $param Column to order
     * @internal param string $order Order direction
     * @return \Illuminate\View\View
     */
    public function getAll(Request $request)
    {
        $search = $request->input('search');
        if(is_null($search)){
            $query = User::getAll(true, true);
        }else{
            $query = User::search($search);
        }

        return $this->all(
            $request,
            $query,
            'admin/users',
            trans('users.all_title'),
            trans('users.delete_message'),
            'users.all'
        );
    }

    /**
     * Handles search
     *
     * @param SearchRequest $request
     *
     * @return \Illuminate\View\View
     */
    public function postSearch(SearchRequest $request)
    {
        return $this->getAll(
            $request,
            $request->input('search'),
            null,
            null
        );
    }

    /**
     * Deletes user
     *
     * @param int $id User id
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function getDelete($id)
    {
        $user = User::where('id', $id)->withTrashed()->first();

        if ($user->hasRole('admin') && count($user->getAdmins(false, true)) <= 1) {
            flash()->error(trans('users.can_not_delete'));

            return redirect()->back();
        } else {
            UserRole::where('user_id', $id)->delete();

            User::flushCache($user);

            $user->delete();

            flash()->success(trans('users.delete_success'));

            return redirect()->back();
        }
    }

    /**
     * Renders add user form
     *
     * @return \Illuminate\View\View
     */
    public function getAdd()
    {
        $roles = Role::all();

        return $this->render('users.add', ['roles' => $roles]);
    }

    /**
     * Adds an user
     *
     * @param AddUserRequest $request
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function postAdd(AddRequest $request)
    {
        $user = new User();

        $user->changeProfile($request);
        $user->roles()->attach($request->input('roles'));
        $user->changeSettings($request);

        if ($request->file('avatar') && Settings::get('use_avatars')) {
            $response = ToIcr::uploadImage($request->file('avatar'), 'avatar');

            if ($response instanceof \Exception) {
                flash()->error($response->getMessage());

                return redirect()->back();
            }

            $user->changeAvatar($response);
        }

        $user->save();

        User::flushCache($user);

        flash()->success(trans('users.add_success'));

        return redirect()->back();
    }

    /**
     * Renders edit user page
     *
     * @param int $id User id
     *
     * @return \Illuminate\View\View
     */
    public function getEdit($id)
    {
        $user = User::getUser($id, true);
        $roles = Role::all();

        return $this->render(
            'users.edit',
            [
                'user' => $user,
                'roles' => $roles,
            ]
        );
    }

    /**
     * Handles user edit
     *
     * @param EditUserRequest $request
     * @param int $id User id
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function putEdit(EditRequest $request, $id)
    {
        $user = User::find($id);
        $user->changeProfile($request);

        if (
            $user->hasRole('admin') &&
            count($user->getAdmins(false, true)) <= 1 &&
            (!in_array(1, $request->input('roles')) || !$request->input('active'))
        ) {
            flash()->error(trans('users.can_not_edit'));

            return redirect()->back();
        } else {
            UserRole::where('user_id', $user->id)->delete();
            $user->roles()->attach($request->input('roles'));
            $user->changeSettings($request);
        }

        if ($request->file('avatar') && Settings::get('use_avatars')) {
            $response = ToIcr::uploadImage($request->file('avatar'), 'avatar');

            if ($response instanceof \Exception) {
                flash()->error($response->getMessage());

                return redirect()->back();
            }

            $user->changeAvatar($response);
        }

        $user->save();

        User::flushCache($user);

        flash()->success(trans('users.edit_success'));

        return redirect()->back();
    }

    /**
     * Deletes user avatar
     *
     * @param int $id User id
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function getDeleteAvatar($id)
    {
        if (Settings::get('use_avatars')) {
            $user = User::find($id);

            $response = ToIcr::deleteImage($user->avatar, 'avatar');

            if ($response instanceof \Exception) {
                flash()->error($response->getMessage());

                return redirect()->back();
            }

            $user->deleteAvatar();
            $user->save();

            flash()->success(trans('users.avatar_deleted'));
            User::flushCache($user);
        }

        return redirect()->back();
    }

    /**
     * Disable user
     *
     * @param int $id User id
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function getDisable($id)
    {
        $user = User::find($id);

        if (
            $user->hasRole('admin') &&
            count($user->getAdmins(false, true)) <= 1
        ) {
            flash()->error(trans('users.can_not_deactivate'));

            return redirect()->back();
        } else {
            $user->delete();

            flash()->success(trans('users.disabled_success'));

            User::flushCache($user);

            return redirect()->back();
        }
    }

    /**
     * Activates user
     *
     * @param int $id User id
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function getActivate($id)
    {
        $user = User::getUser($id, true);

        $user->deleted_at = null;
        $user->save();

        User::flushCache($user);

        flash()->success(trans('users.activated_success'));

        return redirect()->back();
    }

}
